package org.xin.security.config.handle;

import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.xin.common.result.Result;
import org.xin.common.result.ResultCode;
import org.xin.common.util.ClientUtil;
import org.xin.common.util.XinUtil;
import org.xin.security.pojo.bo.SecurityUser;
import org.xin.security.component.TokenComponent;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：xin
 * @date ：Created in 2021/10/2
 * @desc <p> 自定义退出处理类 返回成功 </p>
 * @modified By：$
 * @version: $
 */
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    @Autowired
    private TokenComponent tokenComponent;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SecurityUser securityUser = tokenComponent.getSecurityUser(request);
        if (XinUtil.noNull(securityUser)) {
            String userName = securityUser.getUsername();
            // 删除用户缓存记录
            tokenComponent.delSecurityUser(securityUser.getToken());
            // 记录用户退出日志
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
        }
        ClientUtil.renderString(response, JSONUtil.toJsonStr(Result.error(ResultCode.SUCCESS, "退出成功")));
    }
}
